package designpattern.observer.livedemo;

import java.util.ArrayList;
import java.util.List;

public class Calculator {
    private List<CalculationObserver> observers = new ArrayList<>();

    // 添加观察者方法
    public void addObserver(CalculationObserver observer) {
        observers.add(observer);
    }

    // 移除观察者方法
    public void removeObserver(CalculationObserver observer) {
        observers.remove(observer);
    }

    // 通知所有观察者进度变化
    private void notifyProgress(int step, int totalSteps) {
        for (CalculationObserver observer : observers) {
            observer.onProgressChanged(step, totalSteps);
        }
    }

    // 通知所有观察者计算完成
    private void notifyComplete(float result) {
        for (CalculationObserver observer : observers) {
            observer.onCalculationComplete(result);
        }
    }

    public float calc() throws InterruptedException {
        int totalSteps = 10;
        for (int i = 0; i < totalSteps; i++) {
            // perform complex calculation
            Thread.sleep(1000);
            notifyProgress(i + 1, totalSteps);
        }

        float result = 10;
        notifyComplete(result);
        return result;
    }
}
